package com.lagou.request;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        int i = in.readInt();
        byte[] bytes = new byte[i];
        in.readBytes(bytes);
        Object deserialize = serializer.deserialize(clazz, bytes);
        if (deserialize == null) {
            return;
        }
        RpcRequest rpcRequest = (RpcRequest) serializer.deserialize(clazz, bytes);
        out.add(rpcRequest);
//        RpcRequest rpcRequest = (RpcRequest) serializer.deserialize(clazz, byteBuf.array());
    }
}
